<?php

set_time_limit(0);

require 'WebSocket.php';

$server = new PHPWebSocket;

$server->bind('open', 'onOpen');
$server->bind('message', 'onMessage');
$server->bind('close', 'onClose');

$server->wsStartServer('127.0.0.1', 9311);

function onOpen($clientId)
{
    global $server;

    $ip = long2ip($server->wsClients[$clientId][6]);

    $server->log("{$ip} ({$clientId}) has connected.");

    $clients = $server->wsClients;
    foreach ($clients as $id => $client) {
        if ($id != $clientId) {
            $server->wsSend($id, "Visitor {$clientId} ({$ip}) has joined the room.");
        }
    }
}

function onMessage($clientId, $message, $messageLength, $binary)
{
    global $server;

    $ip = long2ip($server->wsClients[$clientId][6]);

    if ($messageLength == 0) {
        var_dump('on close');
        // $server->wsClose($clientId);

        return;
    }

    if (sizeof($server->wsClients) == 1) {
        $server->wsSend($clientId, "There isn't anyone else in the room, but I'll still listen to you. --Your Trusty Server");
    } else {
        $clients = $server->wsClients;
        foreach ($clients as $id => $client) {
            if ($id != $clientId) {
                $server->wsSend($id, "Visitor {$clientId} ({$ip}) said {$message}");
            }
        }
    }
}

function onClose($clientId, $status)
{
    global $server;

    $ip = long2ip($server->wsClients[$clientId][6]);

    $server->log("{$ip} ({$clientId}) has disconncted.");

    $clients = $server->wsClients;
    foreach ($clients as $id => $client) {
        $server->wsSend($id, "Visitor {$clientId} ($ip) has left the room.");
    }
}
